import React, {useState, useEffect} from 'react';
import {ListView, Card, Flex, Grid, Modal} from 'antd-mobile';
import {fetchAppraisal, getImageById} from '../../api/index'

interface Props {
    partyId: any;
    history: any
}

function MyBody(props: any) {
    return <div className="myp-drop">{props.children}</div>;
}

function SmallBody(props: any) {
    return <div style={{margin: '8px'}}> {props.children} </div>;
}

async function loadingBatchImage(array: any) {
    return new Promise(async resolve => {
        const imageList = array;
        let resultList = []
        if (imageList.length > 0) {
            for (let i = 0; i < imageList.length; i++) {
                const item = imageList[i]
                let result: any = await getImageById(item);

                resultList.push({
                    icon: result.data.content,
                    text: `name${i}`,
                })
            }

        }
        resolve(resultList)
    })
}

const AppraisalList = (Props: Props) => {
    const [offset, setOffset] = useState(0);
    const [limit, setLimit] = useState(10);
    const [totalSize, setTotalSize] = useState(0);
    const [refreshing, setRefreShing] = useState(true)
    const [list, setList] = useState([])
    const [partyId, setPartyId] = useState('')
    const [dataSource, setDataSource] = useState(new ListView.DataSource({
        rowHasChanged: (row1: any, row2: any) => row1 !== row2,
    }))
    const [isLoading, setIsLoading] = useState(false)
    const [hasMore, setHasMore] = useState(false)
    useEffect(() => {
        const id = Props.partyId;
        if (!!id && !partyId) {
            setPartyId(id);
            loadData(id);
        }
    });

    function loadData(id: any, offsets: number = 0) {
        const queryParams = {
            query: ` (partyId ==  ${id} ) sortby metadata.createdDate/sort.descending `,
            offset: offsets * limit,
            limit: limit
        }
        fetchAppraisal(queryParams).then((response: any) => {
            const appraisalGroup = response.data.appraisalGroup;
            if (!!appraisalGroup) {
                const dataList = list.concat(appraisalGroup);
                if (dataList.length <= response.data.totalRecords) {
                    setHasMore(true);
                } else {
                    setHasMore(false);
                }
                setList(dataList);
                setTotalSize(response.data.totalRecords);
                setDataSource(dataSource.cloneWithRows(dataList));
                setIsLoading(false);
                setRefreShing(false)
            } else {
                setRefreShing(false);
                setHasMore(false);
                setIsLoading(false);
            }
        })
    }

    function onEndReached(event: any) {
        const Noffset = offset + 1;

        if (isLoading || !hasMore) {
            return;
        }
        setIsLoading(true);
        setOffset(Noffset);
        loadData(partyId, Noffset);
    }


    const row = (rowData: any, sectionID: any, rowID: any) => {
        const username = rowData.readerReserveGroup[0].name
        let name = username.substr(0, username.split('').length / 2) + '******' + username.substr(username.split('').length / 2 + 3, username.split('').length)
        const score = parseInt(rowData.score)
        const starNode: any = []
        for (let i = 0; i < score; i++) {
            starNode.push(
                <label style={{zoom: 0.4, float: "none", backgroundImage: 'url(/images/icons/star-x.png)'}}></label>
            )
        }
        return (
            <Card key={`${sectionID}-${rowID}`}>
                <Card.Header
                    title={
                        <Flex style={{fontSize: '.1rem'}}>
                            <Flex.Item style={{width: 240}}>

                                <fieldset className="starability-slot" style={{width: '100%'}}>

                                    <div style={{width: 35, float: 'left', margin: 4}}>
                                        <a>
                                            <img src=" /images/user-img.png"/>
                                        </a>
                                    </div>

                                    <div style={{marginBottom: 2, fontSize: '.2rem'}}>{name} </div>
                                    <span style={{color: '#777', fontSize: '.2rem'}}>{rowData.createDate}</span>
                                    <i style={{
                                        borderRight: '1px solid #9e9e9e59',
                                        marginLeft: '8px',
                                        marginRight: 8
                                    }}></i>
                                    {
                                        starNode.map((item: any) => {
                                            return item
                                        })
                                    }
                                </fieldset>
                            </Flex.Item>

                        </Flex>
                    }
                />
                <Card.Body>
                    <div style={{fontSize: '.2rem'}}>
                        <p onClick={() => {
                            Props.history.push('/appraisal_detail/' + rowData.id);
                        }}>
                            {rowData.appraisal}
                        </p>

                        <div id={rowData.id}>
                            {

                                rowData.imageIdList.length > 0 && <a onClick={() => {

                                    loadingBatchImage(rowData.imageIdList).then((res: any) => {

                                        return Modal.alert("评论图片", <Grid data={res}
                                                                         columnNum={2}
                                                                         renderItem={dataItem => (
                                                                             <div style={{padding: '12.5px'}}>
                                                                                 <img src={dataItem!.icon} style={{
                                                                                     width: '100px',
                                                                                     height: '100px'
                                                                                 }} alt=""/>
                                                                                 <div style={{
                                                                                     color: '#888',
                                                                                     fontSize: '14px',
                                                                                     marginTop: '12px'
                                                                                 }}>

                                                                                 </div>
                                                                             </div>
                                                                         )}
                                        />)
                                    })


                                }} style={{color: 'red'}}>
                                    点击查看图片
                                </a>

                            }

                        </div>

                    </div>
                </Card.Body>
            </Card>
        );
    };
    let heightSize = 100;
    if (list.length > 0) {
        heightSize = window.innerHeight
    }
    return (
        <ListView
            dataSource={dataSource}
            renderFooter={() => (<div style={{padding: 30, textAlign: 'center'}}>
                {isLoading ? '加载中...' : '下面没有了(>^ω^<)喵'}
            </div>)}
            style={{height: heightSize, width: '100%'}}
            renderRow={row}
            className="am-list sticky-list"
            initialListSize={10}
            pageSize={10}
            onEndReachedThreshold={50}
            onEndReached={onEndReached}
            renderBodyComponent={() => <MyBody/>}
            renderSectionBodyWrapper={() => <SmallBody/>}
        />

    )
}

export default AppraisalList;